package com.cqw.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Stream;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-06-02 17:44
 * @Description:
 */
@Configuration
@MapperScan(basePackages = {"com.cqw.mapper.one", "com.cqw.order.mapper"}, sqlSessionFactoryRef = "oneSqlSessionFactory")
public class OneDateSourceConfig {


    @Bean("oneDataSource")
    @ConfigurationProperties(prefix = "common.datasources.one")
    @Primary
    public DataSource getDbDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        return druidDataSource;
    }

    @Bean("oneSqlSessionFactory")
    public SqlSessionFactory db1SqlSessionFactory(@Qualifier("oneDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        String[] locationArr = {"classpath*:mapper/one/*.xml", "classpath*:mapper/order/*.xml"};
        Resource[] resources = Arrays.stream(locationArr).flatMap(location -> {
            try {
                return Stream.of(new PathMatchingResourcePatternResolver().getResources(location));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }).toArray(Resource[]::new);
        bean.setMapperLocations(resources);
        return bean.getObject();
    }

    @Bean("oneTransactionManager")
    @Primary
    public DataSourceTransactionManager sourceTransactionManager(@Qualifier("oneDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean("oneSqlSessionTemplate")
    public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("oneSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
